var wiggleMaxLength = function(nums) {
  const len = nums.length;
  if (len < 2) return len;
  
  // 代表上轮趋势
  let trend;

  let i = 1;
  let ans = 1;
  while (i++ < nums.length) {
    if (nums[i] !== nums[i - 1]) {
      if (nums[i] > nums[i - 1] !== trend) {
          ans++;
          trend = nums[i] > nums[i - 1];
      }
    }
  } 
  return ans;
};

const nums = [1,7,4,9,2,5];
console.log(wiggleMaxLength(nums));

// 动态规划
// di[i][0]表示以i为波谷的最长长度
// di[i][1]表示以i为波峰的最长长度
function fn2(nums) {
  const len = nums.length;
  if (len < 2) return len;

  const dp = new Array(len).fill(0).map(() => new Array(2).fill(1));

  for(let i = 1; i < len; i++) {
    for (let j = 0; j < i; j++) {
      if (nums[i] < nums[j]) dp[i][0] = Math.max(dp[i][0], dp[j][1] + 1);
      if (nums[i] > nums[j]) dp[i][1] = Math.max(dp[i][1], dp[j][0] + 1);
    }
  }
  return Math.max(dp[len - 1][1], dp[len - 1][0])
}
console.log(fn2(nums));